package xhwl.insurance.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.R;
import xhwl.insurance.adapter.AllCardDealAdapter;
import xhwl.insurance.customView.PullToRefreshListView;
import xhwl.insurance.db.SaleInfoDao;
import xhwl.insurance.db.bean.SaleInfo;
import xhwl.insurance.http.api.ProcessInfoApi;
import xhwl.insurance.http.api.ProcessListApi;
import xhwl.insurance.http.bean.resp.ProcessInfoResp;
import xhwl.insurance.http.bean.resp.ProcessListResp;
import xhwl.insurance.http.bean.resp2.HttpResp;
import xhwl.insurance.ui.CardDealDetialActivity;
import xhwl.insurance.ui.CardDealListActivity;
import xhwl.insurance.ui.SubmitCachedSaleInfoActivity;
import xhwl.insurance.ui.UpdateSaleInfoActivity;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by admin on 2017/7/31.
 */

public class AllCardDealFragment extends BaseFragment implements PullToRefreshListView.RefreshListener
 ,AdapterView.OnItemClickListener{
    ArrayList<ProcessListResp> mList = new ArrayList<ProcessListResp>();
    PullToRefreshListView pullToRefreshListView;
    private AllCardDealAdapter adapter;
    private String memberId;
    private String orderStatus;//""-全部 0=处理中 3=无效 1=成功 4-失败
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderStatus=getArguments().getString("orderStatus");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        if(isVisibleToUser){
//            //只有当该Fragment被用户可见的时候,才加载网络数据
//            orderStatus=getArguments().getString("orderStatus");
//            getLoad(1);
//        }else{
//            //否则不加载网络数据
//        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return LayoutInflater.from(mActivity).inflate(
                R.layout.fragement_allorder_layout, null);
    }

    @Override
    protected void initView(View view) {
        initTitleViews(view);
        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.allorder_pullToRefreshListView);
        if("4".equals(orderStatus)){
            pullToRefreshListView.setEnablePullLoadMoreDataStatus(false);
            pullToRefreshListView.setEnablePullTorefresh(false);
        }
    }
    @Override
    protected void setUpTitleView() {
        titleTextView.setText("全部订单");
        super.setUpTitleView();
    }

    @Override
    protected void initListener() {
        pullToRefreshListView.setRefreshListener(this);
        pullToRefreshListView.setOnItemClickListener(this);
    }

    @Override
    protected void loadData() {
        getLoad(1);
    }

    @Override
    protected void processOper() {
        adapter = new AllCardDealAdapter(mActivity, mList);
        pullToRefreshListView.setAdapter(adapter);
    }

    public void onRefresh(int page) {
        getLoad(page);

    }
    private ArrayList<ProcessListResp> getSavedList(){//提交失败，根据缓存数据构造列表数据
        ArrayList<ProcessListResp> respList=new ArrayList<>();
        String member_id= SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID,"");
        SaleInfoDao saleInfoDao=new SaleInfoDao(mActivity);
        List<SaleInfo> saleInfoList = saleInfoDao.findAllFailed(member_id);
        for(SaleInfo info:saleInfoList){
            ProcessListResp resp=new ProcessListResp();
            resp.setORDER_STATUS("提交失败");
            resp.setPERSON_NAME(info.person_name);
            resp.setCREATE_DATE(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(info.create_time));
            resp.setSALE_NAME(info.card_name);
            resp.savedSaleInfo=info;
            respList.add(resp);
        }
        return respList;
    }
    public void getLoad(final int page){
        String linkMobile = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.LINK_MOBILE,null);
        if (StringUtil.isEmpty(linkMobile)) {
            return;
        }
        if("4".equals(orderStatus)){
            ArrayList<ProcessListResp> respList=getSavedList();
            pullToRefreshListView.onRefreshComplete(mList, respList.size(),R.drawable.nodata_default);
            if (null != respList && 0 < respList.size()){
                Collections.sort(respList);
                mList.addAll(respList);
            }
            adapter.notifyDataSetChanged();
        }
        else
        {

            ProcessListApi api = new ProcessListApi(linkMobile,orderStatus,page);
            HttpManager.getInstance().dealHttp(this,api,new OnNextListener<HttpResp<ArrayList<ProcessListResp>>>(){
//                @Override
//                public void onNext(ArrayList<ProcessListResp> resp) {
//                    try {
//                        if("".equals(orderStatus)&&page==1){//全部数据列表加上缓存列表
//                            resp.addAll(getSavedList());
//                        }
//                        pullToRefreshListView.onRefreshComplete(mList, resp.size(),R.drawable.nodata_default);
//                        if (null != resp && 0 < resp.size()){
//                            Collections.sort(resp);
//                            mList.addAll(resp);
//                            if("".equals(orderStatus)){
//                                //对list按时间排序
//                            }
//                            adapter.notifyDataSetChanged();
//                        }
//                    } catch (Exception e) {
//                        // TODO: handle exception
//                        XHLog.e(e.getMessage());
//                        pullToRefreshListView.onRefreshComplete();
//                    }
//                }

                @Override
                public void onNext(HttpResp<ArrayList<ProcessListResp>> arrayListHttpResp) {
                    if (arrayListHttpResp != null) {
                        if (arrayListHttpResp.isOk()) {
                            if (arrayListHttpResp.data != null && arrayListHttpResp.data.size() > 0) {
                                try {
                                    if ("".equals(orderStatus) && page == 1) {
                                        arrayListHttpResp.data.addAll(getSavedList());
                                    }
                                    pullToRefreshListView.onRefreshComplete(mList, arrayListHttpResp.data.size(), R.drawable.nodata_default);
                                    if (null != arrayListHttpResp && 0 < arrayListHttpResp.data.size()) {
                                        Collections.sort(arrayListHttpResp.data);
                                        mList.addAll(arrayListHttpResp.data);
                                        if ("".equals(orderStatus)) {
                                            //对list按时间排序
                                        }
                                        adapter.notifyDataSetChanged();
                                    }
                                } catch (Exception e) {
                                    XHLog.e(e.getMessage());
                                    pullToRefreshListView.onRefreshComplete();
                                }
                            }
                        }
                    }
                }

                @Override
                public void onError(HttpException ex) {
                    super.onError(ex);
                    pullToRefreshListView.onRefreshComplete();
                    if("".equals(orderStatus)&&page==1){//全部数据列表加上缓存列表
                        ArrayList<ProcessListResp> respList=getSavedList();
                        pullToRefreshListView.onRefreshComplete(mList, respList.size(),R.drawable.nodata_default);
                        if (null != respList && 0 < respList.size()){
                            Collections.sort(respList);
                            mList.addAll(respList);
                        }
                        adapter.notifyDataSetChanged();
                    }
                }
            });

        }

    }
    public void onDestroy() {
        super.onDestroy();
    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final ProcessListResp bean = mList.get(position);
        if("处理中".equals(bean.getORDER_STATUS())){//十分钟内可修改
            ProcessInfoApi api=new ProcessInfoApi(bean.BUY_ID);
            HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ProcessInfoResp>() {
                @Override
                public void onNext(ProcessInfoResp resp) {
                    if("001".equals(resp.code)){
//                        final ProcessInfoResp.ProcessInfo info=new Gson().fromJson(resp.info,ProcessInfoResp.ProcessInfo.class);
                        final ProcessInfoResp.ProcessInfo info=resp.info;
                        Intent intent = new Intent(mActivity, UpdateSaleInfoActivity.class);
                        intent.putExtra(UpdateSaleInfoActivity.EXTRA_DATA,info);
                        startActivity(intent);


                    }else if("002".equals(resp.code)){//超时订单
                        Intent intent = new Intent(mActivity, CardDealDetialActivity.class);
                        intent.putExtra(CardDealDetialActivity.BEAN,bean);
                        startActivity(intent);


                    }else if("003".equals(resp.code)){
                        ToastUtil.showToast(mActivity,"订单无效，没有此订单");
                    }
                    else if("00010".equals(resp.error_code)){
                        ToastUtil.showToast(mActivity,"订单无效,buy_id为空");
                    }
                }
            });
        }
        else if("提交失败".equals(bean.getORDER_STATUS())){
            SaleInfo info=bean.savedSaleInfo;
            //调用修改界面
            Intent intent=new Intent(mActivity, SubmitCachedSaleInfoActivity.class);
            intent.putExtra(SubmitCachedSaleInfoActivity.EXTRA_DATA,info.id);
            startActivity(intent);
        }
        else

        {
            Intent intent = new Intent(mActivity, CardDealDetialActivity.class);
            intent.putExtra(CardDealDetialActivity.BEAN,bean);
            startActivity(intent);

        }

    }
}
